<!--
 * @Author: jiangyg email@jiangyg.com
 * @Date: 2022-08-14 15:31:12
 * @LastEditors: jiangyg email@jiangyg.com
 * @LastEditTime: 2022-11-21 06:25:38
 * @FilePath: /frontend/mall-frontend/src/views/modules/admin/ware/purchase-assignee.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-dialog :title="`采购单[${dataForm.id}]任务分配`" width="40%" draggable :close-on-click-modal="false" v-model="visible">
    <el-form ref="dataFormRef" :model="dataForm" :rules="dataRule" @keyup.enter="dataFormSubmit(dataFormRef)" label-width="80px">
      <el-form-item label="分配人员" prop="assigneeId">
        <user-select v-model="dataForm.assigneeId" ref="userSelectRef" @change="handleAssigneeChangeEvent" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="ad-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button type="primary" @click="dataFormSubmit(dataFormRef)" :disabled="submitted">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import http from "@/utils/httpRequest";
import validate from "@/utils/validate";
import type { FormInstance } from "element-plus";
import { ref, reactive, nextTick, defineExpose, defineEmits } from "vue";

import UserSelect from "../common/user-select.vue";

// 弹窗是否显示
const visible = ref(false);

// 提交状态
const submitted = ref(false);

// 表单数据
const dataForm = reactive({
  // 采购单ID
  id: "",
  // 分配人员ID
  assigneeId: "",
  // 分配人员名称
  assigneeName: "",
});

// 数据校验规则
const dataRule = reactive({
  assigneeId: validate.required("分配人员"),
});

// 表单引用
const dataFormRef = ref<FormInstance>();

// 分配人员引用
const userSelectRef = ref();

// 父级组件的自定义事件
const emit = defineEmits(['loadTableData']);

// 初始化表单
const initForm = async (d) => {
  // 表单数据初始化
  dataForm.id = d.id;
  visible.value = true;
  dataForm.assigneeId = d.assigneeId;
  await nextTick();
  userSelectRef.value.init(d.assigneeId);
};

// 表单提交
const dataFormSubmit = (form: FormInstance | undefined) => {
  if (submitted.value) {
    return;
  }
  form.validate((valid) => {
    if (valid) {
      submitted.value = true;
      http
        .post({
          url: `/ware/purchase/assignee`,
          data: dataForm,
        })
        .then(({ data }) => {
          if (http.success(data, true, true)) {
            visible.value = false;
            emit("loadTableData");
            return;
          }
          submitted.value = false;
        });
    }
  });
};

// 处理分配人变化事件
const handleAssigneeChangeEvent = (data) => {
  dataForm.assigneeName = data.username;
};

// 暴露方法
defineExpose({ initForm });
</script>
